<?php
     /**
      * Simple logger class based on a similer class created by 
      * Darko Bunic (http://www.redips.net/php/write-to-log-file/)     
      * Does simple logging to a specified file. See https://bitbucket.org/huntlyc/simple-php-logger for more details.
      *
      * @package default
      * @author Huntly Cameron <huntly.cameron@gmail.com>
      **/
	error_reporting(0);
	define('LEVEL_FATAL', 0);
	define('LEVEL_ERROR', 1);
	define('LEVEL_WARN', 2);
	define('LEVEL_INFO', 3); 
	define('LEVEL_DEBUG', 4);  
    class Logger{
        /**
         * log_file - the log file to write to
         *  
         * @var string
         **/ 

		private $log_dir;		 
        private $log_file;
		private $level = LEVEL_DEBUG;
        
        /**
         * Constructor
         * @param String logfile - [optional] Absolute file name/path. Defaults to ubuntu apache log.
         * @return void
         **/        
        function __construct($type) {
			//设置日志文件夹
			$this->setLogDir();
			//设置日志文件
			$this->setLogFile($type);
           
            //Make sure we'ge got permissions
            if(!(is_writable($this->log_file) || $this->win_is_writable($this->log_file))){   
                //Cant write to file,
                throw new Exception("LOGGER ERROR: Can't write to log", 1);
            }
        }
		
		
		public function setLogDir(){
			$date = date('Ymd',time());
			if( !is_dir("logs") ){
			    if( mkdir("logs") ){
			        chmod("logs",0777);
			    }
			}
			if ( !is_dir("logs/$date") ){
				//创建日志文件夹
				if ( mkdir("logs/$date") ){
					//权限
					if (chmod("logs/$date",0777) ){
						
						$this->log_dir = "logs/$date";
					}else{
						
						echo "赋权限失败----LOGGER";
					}
					
				}else{
					
					echo "创建文件夹失败----LOGGER";
				}
			}else{
				$this->log_dir = "logs/$date";
			}
		}
		
		public function setLogFile($type){
			if (!in_array($type,array('info','error','debug'))){
				echo "参数错误----LOOGGER";
			}
            $handler = opendir($this->log_dir);
			while (($filename = readdir($handler)) !== false) {//务必使用!==，防止目录下出现类似文件名“0”等情况  
				if ($filename != "." && $filename != "..") {  
					$files[] = $filename ;  
				}  
			}  
			closedir($handler); 
			
			if (!empty($files)){
				$info = array();
				$debug = array();
				$error = array();
				foreach($files as $v){
					if (preg_match('/info_\d.log/',$v,$matchs)){
						$info[] = $matchs[0];
					}	
					if (preg_match('/debug_\d.log/',$v,$matchs)){
						$debug[] = $matchs[0];
					}
					if (preg_match('/error_\d.log/',$v,$matchs)){
						$error[] = $matchs[0];
					}
				}
				switch($type)
				{
					case 'info' :
						if(count($info)>0){
							$log_file = $this->log_dir .'/info_'.count($info).'.log';
						}else{
							$log_file = $this->log_dir .'/info_1'.'.log';
						}
						break;
					
					case 'debug':
						if(count($debug)>0){
							$log_file = $this->log_dir .'/debug_'.count($debug).'.log';
						}else{
							$log_file = $this->log_dir .'/debug_1'.'.log';
						}
						break;
					
					case 'error':
					    if(count($error)>0){
							$log_file = $this->log_dir .'/error_'.count($error).'.log';
						}else{
							$log_file = $this->log_dir .'/error_1'.'.log';
						}
						break;
					
				}
				
				touch($log_file);
				chmod($log_file,0777);
				
				if (file_exists($log_file) && filesize($log_file) >30 * 1024 * 1024) {
					$index = count($$type) + 1;	
					$s_file_name = $type.'_'. $index .'.log';
					$log_file = $this->log_dir.'/'.$s_file_name;
					touch($log_file);
					chmod($log_file,0777);
				}
			}else{
				$log_file = $this->log_dir .'/'.$type.'_1'.'.log';
				touch($log_file);
				chmod($log_file,0777);
			}

			$this->log_file = $log_file;
		}
		

		public function setLevel($status) {
			$this->level = $status;
		}
        /**
         * debug - Log Debug
         * @param String tag - Log Tag
         * @param String message - message to spit out
         * @return void
         **/      
        public function debug($tag, $message){
            $this->writeToLog("DEBUG", LEVEL_DEBUG, $tag, $message);
        }
		
        /**
         * info - Log Info
         * @param String tag - Log Tag
         * @param String message - message to spit out
         * @return void
         **/        
        public function info($tag, $message){
            $this->writeToLog("INFO", LEVEL_INFO, $tag, $message);            
        }
		
        /**
         * warn - Log Warning
         * @param String tag - Log Tag
         * @param String message - message to spit out
         * @author 
         **/        
        public function warn($tag, $message){
            $this->writeToLog("WARN", LEVEL_WARN, $tag, $message);            
        }
		
        /**
         * error - Log Error
         * @param String tag - Log Tag
         * @param String message - message to spit out
         * @author 
         **/        
        public function error($tag, $message){
            $this->writeToLog("ERROR", LEVEL_ERROR, $tag, $message);            
        }
		
        /**
         * fatal - Log Fatal
         * @param String tag - Log Tag
         * @param String message - message to spit out
         * @author 
         **/        
        public function fatal($tag, $message){
            $this->writeToLog("FATAL", LEVEL_FATAL, $tag, $message);            
        }
		
        /**
         * writeToLog - writes out timestamped message to the log file as 
         * defined by the $log_file class variable.
         *
         * @param String status - "INFO"/"DEBUG"/"ERROR" e.t.c.
         * @param String tag - "Small tag to help find log entries"
         * @param String message - The message you want to output.
         * @return void
         **/        
        private function writeToLog($status, $level, $tag, $message) {
			if ($level <= $this->level) {
	            $date = date('[Y-m-d H:i:s]');
	            $msg = "$date: [$tag][$status] - $message" . PHP_EOL;
	            file_put_contents($this->log_file, $msg, FILE_APPEND);
			}
        }

        //Function lifted from wordpress
        //see: http://core.trac.wordpress.org/browser/tags/3.3/wp-admin/includes/misc.php#L537
        private function win_is_writable( $path ) {
            /* will work in despite of Windows ACLs bug
             * NOTE: use a trailing slash for folders!!!
             * see http://bugs.php.net/bug.php?id=27609
             * see http://bugs.php.net/bug.php?id=30931
             */
            if ( $path[strlen( $path ) - 1] == '/' ) // recursively return a temporary file path
                return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
            else if ( is_dir( $path ) )
                return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
            
            // check tmp file for read/write capabilities
            $should_delete_tmp_file = !file_exists( $path );
            $f = @fopen( $path, 'a' );
            if ( $f === false )
                return false;
            
            fclose( $f );

            if ( $should_delete_tmp_file )
                unlink( $path );

            return true;
        }        
    }
?>
